from rest_framework import serializers
from django.contrib.auth.models import User
from .models import (
    Project,
    Environment,
    ApiInterface,
    TestCase,
    TestExecution,
    TestReport
)


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['id', 'username', 'email']


class ProjectSerializer(serializers.ModelSerializer):
    creator = UserSerializer(read_only=True)

    class Meta:
        model = Project
        fields = '__all__'
        read_only_fields = ['creator', 'created_time', 'updated_time']

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        return super().create(validated_data)


class EnvironmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Environment
        fields = '__all__'


class ApiInterfaceSerializer(serializers.ModelSerializer):
    creator = UserSerializer(read_only=True)

    class Meta:
        model = ApiInterface
        fields = '__all__'
        read_only_fields = ['creator', 'created_time', 'updated_time']

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        return super().create(validated_data)


class TestCaseSerializer(serializers.ModelSerializer):
    creator = UserSerializer(read_only=True)

    class Meta:
        model = TestCase
        fields = '__all__'
        read_only_fields = ['creator', 'created_time', 'updated_time']

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        return super().create(validated_data)


class TestExecutionSerializer(serializers.ModelSerializer):
    executor = UserSerializer(read_only=True)

    class Meta:
        model = TestExecution
        fields = '__all__'
        read_only_fields = ['executor', 'start_time', 'end_time']

    def create(self, validated_data):
        validated_data['executor'] = self.context['request'].user
        return super().create(validated_data)


class TestReportSerializer(serializers.ModelSerializer):
    creator = UserSerializer(read_only=True)
    executions = TestExecutionSerializer(many=True, read_only=True)

    class Meta:
        model = TestReport
        fields = '__all__'
        read_only_fields = ['creator', 'created_time']

    def create(self, validated_data):
        validated_data['creator'] = self.context['request'].user
        return super().create(validated_data) 